const storage = require('../../utils/storage')
const dateUtils = require('../../utils/date')
const { snapshotManager } = require('../../utils/snapshot')
const { debounce } = require('../../utils/debounce')
const keyBoardState = require('../../utils/keyboardstate')

Page({
  data: {
    note: {
      title: '',
      content: { html: '', text: '' },
      category: '',
      createdAt: '',
      updatedAt: '',
      updatedAtText: '',
    },
    options: {},
    categories: [],
    currentCategory: { name: storage.UNCATEGORIZED },
    selectedCategoryIndex: 0,
    keyBoardState: {
      isShow: false,
      height: 0,
      maxHeight: 310
    },
    contentState: { isOnEdit: false, currentLength: 0 }
  },

  onLoad(options) {
    snapshotManager.clear()

    this.initKeyBoardState()

    this.setData({ options })
    setTimeout(() => {
      this.init(options)
      this.initContentState()
      this.initEditor()
    }, 100)
  },

  onShow() {
    getApp().eventBus.emit('onNoteShow')
  },
  onHide(){
    snapshotManager.clear()
  },
  onUnload() {
    snapshotManager.clear()
  },

  initKeyBoardState() {
    keyBoardState.init()
    keyBoardState.on('state', (height) => {
      this.setData({ keyBoardState: { isShow: height > 0, height: height, maxHeight: keyBoardState.getMaxHeight() } })
    })
  },

  formatDate(dateStr) {
    if (new Date(dateStr).getFullYear === new Date().getFullYear) {
      return dateUtils.formatDate(dateStr, 'M月d日 HH:mm')
    }
    else {
      return dateUtils.formatDate(dateStr, 'yyyy年M月d日')
    }
  },

  init(options) {
    // 加载所有分类
    const categories = storage.getCategories().map(name => ({ name }))
    this.setData({ categories })

    // 查找分类索引
    let selectedIndex = categories.findIndex(cat => cat.name === options.category)

    // 如果有传入id，是编辑现有笔记
    if (options.id) {
      // 如果有传入category，直接使用
      if (options.category) {
        const note = storage.getNote(options.category, options.id)
        if (note) {
          if (selectedIndex === -1) selectedIndex = 0

          this.setData({
            note: { ...note, updatedAtText: this.formatDate(note.updatedAt) },
            selectedCategoryIndex: selectedIndex,
            currentCategory: categories[selectedIndex] || { name: storage.UNCATEGORIZED },
            updatedAtText: this.formatDate(note.updatedAt)
          })
        }
      } else {
        // 如果没有传入category，需要查找笔记所在的分类
        for (const cat of categories) {
          const note = storage.getNote(cat.name, options.id)
          if (note) {
            const selectedIndex = categories.findIndex(c => c.name === cat.name)
            this.setData({
              note: { ...note, updatedAtText: this.formatDate(note.updatedAt) },
              selectedCategoryIndex: selectedIndex,
              currentCategory: categories[selectedIndex] || { name: storage.UNCATEGORIZED }
            })
            break
          }
        }
      }
    }
    //新增
    else {
      this.setData({
        selectedCategoryIndex: selectedIndex,
        currentCategory: categories[selectedIndex] || { name: storage.UNCATEGORIZED },
        note: {
          ...this.data.note,
          updatedAt: new Date(), updatedAtText: dateUtils.formatDate(new Date(), 'MM-dd HH:mm')
        }
      })
    }
  },

  navigateBack() {
    wx.navigateBack()
  },

  // 分类选择变化
  onCategoryChange(e) {
    const index = e.detail.value
    this.setData({
      selectedCategoryIndex: index,
      currentCategory: this.data.categories[index]
    })
  },

  initEditor() {
    // 获取editor组件实例
    this.editorCtx = wx.createSelectorQuery().in(this).select('#contentEditor')
      .context((res) => {
        this.editorCtx = res.context;
        this.setEditorContent(this.data.note.content)
      }).exec();
  },

  setEditorContent(content) {
    // 可以是纯文本或带标签的HTML字符串
    const htmlContent = content.html.trim()//.startsWith('<p>') ? content.html : `<p>${content.html}</p>`;

    this.editorCtx.setContents({
      html: htmlContent, // 设置HTML内容
    });
  },

  initContentState() {
    this.setData({ ['contentState.currentLength']: this.data.note.content.text.length })
    snapshotManager.on('add', (data) => {
      this.setContentState()
    })
  },

  setContentState() {
    this.setData({
      contentState: {
        isOnEdit: snapshotManager.hasSnapshot(),
        currentLength: this.data.note.content.text.length
      }
    })
  },

  onTitleInput(e) {
    this.setData({
      'note.title': e.detail.value
    })
    debounce(() => {
      snapshotManager.add('title', e.detail.value)
    })()
  },

  onContentStatusChange(e) {
    // console.log('note.js -> onContentStatusChange -> e: ', e)
  },

  onContentInput(e) {
    let { text, html } = e.detail
    text = text.trim()
    this.setData({
      'note.content': { text, html }
    })
    debounce(() => {
      snapshotManager.add('content', { text, html })
    })()
  },

  onContentFocus() {
    if (snapshotManager.hasSnapshotType('content')) return
    snapshotManager.add('content', this.data.note.content)
  },

  onTitleFocus() {
    if (snapshotManager.hasSnapshotType('title')) return
    if (!this.data.note.title) return
    snapshotManager.add('title', this.data.note.title)
  },

  showFontStyle() {

  },

  deleteNote() {
    const { note, currentCategory } = this.data

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这篇笔记吗？',
      success: (res) => {
        if (res.confirm) {
          storage.deleteNote(currentCategory.name, note.id)
          wx.showToast({
            title: '已删除',
            icon: 'success'
          })

          getApp().eventBus.emit('noteDeleted', note.id)

          setTimeout(() => {
            wx.navigateBack()
          }, 500)
        }
      }
    })
  },

  insertImage() {
    // 从相册或相机选择图片
    wx.chooseMedia({
      count: 9, // 最多选择1张
      mediaType: ['image', 'video'],
      sizeType: ['original', 'compressed'], // 支持原图/压缩图
      sourceType: ['album', 'camera'], // 支持相册/相机
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        res.tempFiles.forEach((file) => {
          // 插入图片到editor中（需先上传图片到服务器，这里简化为直接使用临时路径）
          this.editorCtx.insertImage({
            src: file.tempFilePath,
            width: '95%', // 图片宽度
            success: () => {
            }
          });
        })
      }
    });
  },

  snapshotBack(e) {
    // if (snapshotManager.isFirst()) return
    // const snapshot = snapshotManager.back()
    this.restoreSnapshot(e.detail.value)
  },

  snapshotForward(e) {
    // if (snapshotManager.isEnd()) return
    // const snapshot = snapshotManager.forward()
    this.restoreSnapshot(e.detail.value)
  },

  save(e) {
    const { note, currentCategory } = this.data
    if (!note.title && !note.content.html) {
      wx.showToast({ title: '标题和内容不能都为空', icon: 'none' })
      return
    }

    if (!this.data.contentState.isOnEdit) return

    if (currentCategory.name !== note.category) {
      const fromCategory = note.category
      const toCategory = currentCategory.name
      note.category = currentCategory.name
      storage.moveNoteToCategory(note.id, fromCategory, toCategory)
    }
    const savedNote = storage.saveNote(currentCategory.name, note)

    this.setData({ note: savedNote })

    snapshotManager.clear()

    wx.showToast({ title: '保存成功', icon: 'success' })

    // 触发数据更新事件
    getApp().eventBus.emit('noteUpdated', savedNote)

    setTimeout(() => {
      wx.navigateBack()
    }, 500)
  },

  restoreSnapshot(snapshot) {
    this.setData({ [`note.${snapshot.type}`]: snapshot.content })
    if (snapshot.type === 'content') {
      this.setEditorContent(snapshot.content)
    }
  },

  toggleFontWeight(){
    this.editorCtx.format('Bold')
  },

  toggleFontItalic(){
    this.editorCtx.format('italic')
  }
})